package com.groupbuying.settleproducer.service.impl;

import com.groupbuying.settleproducer.connector.StoreFeign;
import com.groupbuying.settleproducer.connector.SysconfigFeign;
import com.groupbuying.settleproducer.constants.*;
import com.groupbuying.settleproducer.domain.SettleUshopFlowStoreDO;
import com.groupbuying.settleproducer.domain.SettleUshopWithdrawalDO;
import com.groupbuying.settleproducer.domain.SettleUshopWithdrawalYsNativeClearDO;
import com.groupbuying.settleproducer.dto.YSWithdrawalDTO;
import com.groupbuying.settleproducer.service.SettleUshopFlowStoreService;
import com.groupbuying.settleproducer.service.SettleUshopNativePaymentService;
import com.groupbuying.settleproducer.service.SettleUshopWithdrawalService;
import com.groupbuying.settleproducer.service.SettleUshopWithdrawalYsNativeClearService;
import com.groupbuying.settleproducer.utils.DateUtils;
import com.groupbuying.settleproducer.utils.JsonUtils;
import com.groupbuying.settleproducer.utils.apiresult.ApiResult;
import com.groupbuying.settleproducer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @Author: WANGNING
 * @Email wyn20140226@aliyun.com
 * @Date: 2019/6/3 15:54
 * @Des 原生平台线下打款业务处理接口
 */
@Service
public class SettleUshopNativePaymentServiceImpl implements SettleUshopNativePaymentService {
    public static final Logger logger = LoggerFactory.getLogger(SettleUshopNativePaymentServiceImpl.class);
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private StoreFeign storeFeign;
    @Autowired
    private SettleUshopWithdrawalYsNativeClearService withdrawalYsNativeClearService;
    @Autowired
    private SettleUshopWithdrawalService settleWithdrawalService;
    @Autowired
    private SettleUshopFlowStoreService settleUshopFlowStoreService;
    /**
     * @des 原生打款接口业务处理
     * @date 2019/6/3
     * @param map
     * @return com.groupbuying.settleproducer.utils.apiresult.ApiResult
     */
    @Override
    public ApiResult createNativeWithdrawal(Map<String, Object> map) {
        // 解析map参数---商户号--门店id
        Object tempParam = map.get("storeUuid");
        String counterId = tempParam == null ? null : tempParam.toString();
        // 解析map参数---商户生成的订单号
        String outTradeNo = DateUtils.format(new Date(), "yyyyMMdd")+counterId;
        //获取提现id
        String withdrawalId=this.sysconfigFeign.getWithdrawalId();
        // 解析map参数---币种CNY
        String currency = SettleUshopYSWithdrawalQueryEnumConstants.ENUM_CURRENCY_CNY;
        // 解析map参数---原生提现的总金额
        tempParam = map.get("totalAmount");
        String amount = tempParam == null ? null : tempParam.toString();
        BigDecimal totalAmount=new BigDecimal(amount);
        // 解析map参数---订单说明
        tempParam = map.get("subject");
        String subject = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银盛报备商户号
        tempParam = map.get("ysUserCode");
        String merchantUsercode = tempParam == null ? null : tempParam.toString();
        /*-----------获取该商户的银行卡信息---------*/
        // 解析map参数---银行名称
        tempParam = map.get("bankName");
        String bankName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---开户行所在城市
        tempParam = map.get("cityName");
        String cityName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银行帐号
        tempParam = map.get("bankAccountNo");
        String bankAccountNo = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银行帐号用户名
        tempParam = map.get("bankAccountName");
        String bankAccountName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---收款方银行账户类型corporate :对公账户;personal:对私账户
        tempParam = map.get("bankAccountType");
        String bankAccountType = tempParam == null ? null : tempParam.toString();
        // 解析map参数---支持卡类型debit:借记卡;credit:信用卡 unit:单位结算卡
        tempParam = map.get("bankCardType");
        String bankCardType = tempParam == null ? null : tempParam.toString();
        //判断请求参数不为空
        if (StringUtils.isEmpty(counterId) || StringUtils.isEmpty(outTradeNo)
                || StringUtils.isEmpty(currency)|| StringUtils.isEmpty(subject)|| StringUtils.isEmpty(bankName)
                || StringUtils.isEmpty(cityName)|| StringUtils.isEmpty(bankAccountNo)|| StringUtils.isEmpty(bankAccountName)
                || StringUtils.isEmpty(bankAccountType)||StringUtils.isEmpty(bankCardType)) {
            return ApiResult.paramIsNull();
        }
        try {
            int withdrawalYsNativeClearStatus=0;
            SettleUshopWithdrawalYsNativeClearDO withdrawalYsNativeClear =new SettleUshopWithdrawalYsNativeClearDO();
            SettleUshopFlowStoreDO settleUshopFlowStoreDO=new SettleUshopFlowStoreDO();
            //提现平台账户金额
            BigDecimal count=this.settleUshopFlowStoreService.getSumByStoreId(counterId);
            //判断提现金额
            if(totalAmount.compareTo(count)<=0){
                //生成提现信息
                SettleUshopWithdrawalDO settleWithdrawal = new SettleUshopWithdrawalDO();
                settleWithdrawal.setId(withdrawalId);
                settleWithdrawal.setCounterId(counterId);
                settleWithdrawal.setTotalPrice(totalAmount);
                settleWithdrawal.setWithdrawalType(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALTYPE_NOFIRST);
                //暂时平台不需要手续费
                /*String serviceFee=this.sysconfigFeign.getFeeReplace();*/
                settleWithdrawal.setServiceFee(new BigDecimal(0.00));
                settleWithdrawal.setWithdrawalPrice(totalAmount);
                settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_WAIT);
                settleWithdrawal.setGmtCreate(new Date());
                settleWithdrawal.setGmtModified(new Date());
                settleWithdrawal.setPaycompanyBalance(new BigDecimal(0.0));
                settleWithdrawal.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                int settleWithdrawalStatus=this.settleWithdrawalService.save(settleWithdrawal);
                if(settleWithdrawalStatus>0){
                    withdrawalYsNativeClear.setCounterId(counterId);
                    withdrawalYsNativeClear.setWithdrawalId(withdrawalId);
                    withdrawalYsNativeClear.setSplitState(WithdrawalYsNativeClearEnumConstants.ENUM_SPLITSTATE_SUC);
                    withdrawalYsNativeClear.setWithdrawalPrice(totalAmount);
                    withdrawalYsNativeClear.setGmtCreate(new Date());
                    withdrawalYsNativeClear.setGmtModified(new Date());
                    withdrawalYsNativeClear.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                    withdrawalYsNativeClearStatus=this.withdrawalYsNativeClearService.save(withdrawalYsNativeClear);
                    if(withdrawalYsNativeClearStatus>0){
                        settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_SUC);
                        /*插入一条提现记录到分账商户子表中--提现金额为负数*/
                        settleUshopFlowStoreDO.setAmount(totalAmount.multiply(new BigDecimal("-1")));
                        settleUshopFlowStoreDO.setStoreId(counterId);
                        settleUshopFlowStoreDO.setExternalId(withdrawalId);
                        settleUshopFlowStoreDO.setGmtCreate(new Date());
                        settleUshopFlowStoreDO.setGmtModified(new Date());
                        settleUshopFlowStoreDO.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                        settleUshopFlowStoreDO.setFlowType(SettleUshopFlowStoreEnumConstants.ENUM_FLOWTYPE_WITHDRAWAL);
                        settleUshopFlowStoreDO.setNote(SettleUshopFlowStoreEnumConstants.ENUM_WITHDRAWAL_NODE);
                        settleUshopFlowStoreDO.setId(sysconfigFeign.getFlowId());
                        this.settleUshopFlowStoreService.save(settleUshopFlowStoreDO);
                        this.settleWithdrawalService.update(settleWithdrawal);
                        /*拼接提现返回前端提现信息*/
                        YSWithdrawalDTO ysWithdrawalDTO=new YSWithdrawalDTO();
                        ysWithdrawalDTO.setOut_trade_no(outTradeNo);
                        ysWithdrawalDTO.setWithdrawalId(withdrawalId);
                        ysWithdrawalDTO.setSubject(subject);
                        ysWithdrawalDTO.setCurrency(currency);
                        ysWithdrawalDTO.setBank_account_no(bankAccountNo);
                        ysWithdrawalDTO.setBankAccountName(bankAccountName);
                        ysWithdrawalDTO.setBankAccountType(bankAccountType);
                        ysWithdrawalDTO.setBankCardType(bankCardType);
                        ysWithdrawalDTO.setTotal_amount(totalAmount);
                        ysWithdrawalDTO.setBankName(bankName);
                        ysWithdrawalDTO.setCityName(cityName);
                        ysWithdrawalDTO.setCounterId(counterId);
                        logger.info("SettleUshopNativePaymentServiceImpl-->createNativeWithdrawal success!------>save(settleSplitMerchants)");
                        return ApiResult.success(ApiResultCode.SUCCESS, JsonUtils.beanToJson(ysWithdrawalDTO));
                    }else{
                        settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_EXC);
                        withdrawalYsNativeClear.setSplitState(WithdrawalYsNativeClearEnumConstants.ENUM_SPLITSTATE_FAIL);
                        this.withdrawalYsNativeClearService.update(withdrawalYsNativeClear);
                        this.settleWithdrawalService.update(settleWithdrawal);
                        logger.info("SettleUshopNativePaymentServiceImpl-->createNativeWithdrawal failure!------>update(settleWithdrawal)");
                        return ApiResult.failure("提现异常!");
                    }
                }
                settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_FAIL);
                this.settleWithdrawalService.update(settleWithdrawal);
                logger.info("SettleUshopNativePaymentServiceImpl-->createNativeWithdrawal failure!----->update(settleWithdrawal)");
                return ApiResult.failure(settleWithdrawal);

            }else{
                logger.info("SettleUshopNativePaymentServiceImpl-->createNativeWithdrawal failure!----->update(金额不足，请重新输入金额)");
                return ApiResult.failure(0, "金额不足，请重新输入金额", totalAmount);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.error("SettleUshopNativePaymentServiceImpl-->createNativeWithdrawal get Rules fail",e);
        }
        return ApiResult.failure();
    }
}
